/*
 *  Copyright 2008 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.mybatis.generator.internal;

import static org.mybatis.generator.internal.util.StringUtility.isTrue;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.Field;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.InnerClass;
import org.mybatis.generator.api.dom.java.InnerEnum;
import org.mybatis.generator.api.dom.java.JavaElement;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.api.dom.xml.TextElement;
import org.mybatis.generator.api.dom.xml.XmlElement;
import org.mybatis.generator.codegen.mybatis3.IntrospectedTableMyBatis3Impl;
import org.mybatis.generator.config.MergeConstants;
import org.mybatis.generator.config.PropertyRegistry;

/**
 * @author Jeff Butler
 * 
 */
public class DefaultCommentGenerator implements CommentGenerator {

    private Properties properties;
    private boolean suppressDate;
    private boolean suppressAllComments;

    public DefaultCommentGenerator() {
        super();
        properties = new Properties();
        suppressDate = false;
        suppressAllComments = false;
    }

	public void addJavaFileComment(CompilationUnit compilationUnit) {
        // add no file level comments by default
        return;
    }

    /**
     * Adds a suitable comment to warn users that the element was generated, and
     * when it was generated.
     */
    public void addComment(XmlElement xmlElement) {
        if (suppressAllComments) {
            return;
        }

        xmlElement.addElement(new TextElement("<!--")); //$NON-NLS-1$

        StringBuilder sb = new StringBuilder();
        sb.append("  WARNING - "); //$NON-NLS-1$
//        sb.append(MergeConstants.NEW_ELEMENT_TAG);
        xmlElement.addElement(new TextElement(sb.toString()));
        xmlElement
                .addElement(new TextElement(
                        "  		此SQL语句为自动生成，请不要修改.")); //$NON-NLS-1$

        String s = getDateString();
        if (s != null) {
            sb.setLength(0);
            sb.append("  DATE: "); //$NON-NLS-1$
            sb.append(s);
            xmlElement.addElement(new TextElement(sb.toString()));
        }

        xmlElement.addElement(new TextElement("-->")); //$NON-NLS-1$
    }

    public void addRootComment(XmlElement rootElement) {
        // add no document level comments by default
        return;
    }

    public void addConfigurationProperties(Properties properties) {
        this.properties.putAll(properties);

        suppressDate = isTrue(properties
                .getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_DATE));
        
        suppressAllComments = isTrue(properties
                .getProperty(PropertyRegistry.COMMENT_GENERATOR_SUPPRESS_ALL_COMMENTS));
    }

    /**
     * This method adds the custom javadoc tag for. You may do nothing if you do
     * not wish to include the Javadoc tag - however, if you do not include the
     * Javadoc tag then the Java merge capability of the eclipse plugin will
     * break.
     * 
     * @param javaElement
     *            the java element
     */
    protected void addJavadocTag(JavaElement javaElement,
            boolean markAsDoNotDelete) {
//        javaElement.addJavaDocLine(" *"); //$NON-NLS-1$
        StringBuilder sb = new StringBuilder();
        sb.append(" * "); //$NON-NLS-1$
//        sb.append(MergeConstants.NEW_ELEMENT_TAG);
        if (markAsDoNotDelete) {
            sb.append(""); //$NON-NLS-1$
        }
        String s = getDateString();
        if (s != null) {
            sb.append("DATE: ");
            sb.append(s);
        }
        javaElement.addJavaDocLine(sb.toString());
    }

    /**
     * This method returns a formated date string to include in the Javadoc tag
     * and XML comments. You may return null if you do not want the date in
     * these documentation elements.
     * 
     * @return a string representing the current timestamp, or null
     */
    protected String getDateString() {
        if (suppressDate) {
            return null;
        } else {
        	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return sdf.format(new Date());
        }
    }
    //自定义修改
    public void addClassComment(InnerClass innerClass,
            IntrospectedTable introspectedTable) {
	        if (suppressAllComments) {
	            return;
	        }
//        
//        StringBuilder sb = new StringBuilder();
//
//        innerClass.addJavaDocLine("/**"); //$NON-NLS-1$
//        innerClass
//                .addJavaDocLine(" * This class was generated by MyBatis Generator."); //$NON-NLS-1$
//
//        sb.append(" * This class corresponds to the database table "); //$NON-NLS-1$
//        sb.append(introspectedTable.getFullyQualifiedTable());
//        innerClass.addJavaDocLine(sb.toString());
//
//        addJavadocTag(innerClass, false);
//
//        innerClass.addJavaDocLine(" */"); //$NON-NLS-1$
	      SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
    	  innerClass.addJavaDocLine("/**");
    	  innerClass.addJavaDocLine(" * "+introspectedTable.getFullyQualifiedTable().getRemarks());
    	  innerClass.addJavaDocLine(" * "+introspectedTable.getFullyQualifiedTable());
    	  innerClass.addJavaDocLine(" * ");
    	  innerClass.addJavaDocLine(" * @version 1.0 "+sdf.format(new Date()));
    	  innerClass.addJavaDocLine(" */");
    }

    public void addEnumComment(InnerEnum innerEnum,
            IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }

        StringBuilder sb = new StringBuilder();

        innerEnum.addJavaDocLine("/**"); //$NON-NLS-1$
//        innerEnum
//                .addJavaDocLine(" * 此枚举为自动生成."); //$NON-NLS-1$
        innerEnum.addJavaDocLine(" *");
        sb.append(" * TABLE： "); //$NON-NLS-1$
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerEnum.addJavaDocLine(sb.toString());
        
        addJavadocTag(innerEnum, false);

        innerEnum.addJavaDocLine(" */"); //$NON-NLS-1$
    }

    public void addFieldComment(Field field,
            IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }
//
//        StringBuilder sb = new StringBuilder();
//
//        field.addJavaDocLine("/**"); //$NON-NLS-1$
//        field
//                .addJavaDocLine(" * This field was generated by MyBatis Generator."); //$NON-NLS-1$
//
//        sb.append(" * This field corresponds to the database column "); //$NON-NLS-1$
//        sb.append(introspectedTable.getFullyQualifiedTable());
//        sb.append('.');
//        sb.append(introspectedColumn.getActualColumnName());
//        field.addJavaDocLine(sb.toString());
//
//        addJavadocTag(field, false);
//
//        field.addJavaDocLine(" */"); //$NON-NLS-1$
    	  //自定义修改
    	  if(introspectedColumn.getRemarks()!=null && !introspectedColumn.getRemarks().equals("")){
    		  field.addJavaDocLine("/**");
    		  field.addJavaDocLine(" * "+introspectedColumn.getRemarks());
    		  field.addJavaDocLine(" * "+introspectedTable.getFullyQualifiedTable()+"."+introspectedColumn.getActualColumnName());
    		  field.addJavaDocLine(" */");
    	  }
    }

    public void addFieldComment(Field field, IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        StringBuilder sb = new StringBuilder();

        field.addJavaDocLine("/**"); //$NON-NLS-1$
//        field
//                .addJavaDocLine(" * 此字段为自动生成."); //$NON-NLS-1$
        
        if(!field.getName().equals("orderByClause")&& !field.getName().equals("distinct")&& !field.getName().equals("oredCriteria")){
        	if(field.getName().equals("limitStart")){
        		field.addJavaDocLine(" * 分页开始记录数");
        	}else if(field.getName().equals("limitSize")){
        		field.addJavaDocLine(" * 每页显示的记录数");
        	}else{
        		sb.append(" * TABLE： "); //$NON-NLS-1$
                sb.append(introspectedTable.getFullyQualifiedTable());
                field.addJavaDocLine(sb.toString());
        	}
        }
        

        addJavadocTag(field, false);

        field.addJavaDocLine(" */"); //$NON-NLS-1$
    }
    
    
    private String operMethodComment(Method method,IntrospectedTable introspectedTable){
    	String remarks=introspectedTable.getFullyQualifiedTable().getRemarks();
    	String menthodName=method.getName();
    	String result="";
    	if(menthodName.indexOf("delete")>-1){
    		if(menthodName.indexOf("PrimaryKey")>-1){
    			result="通过主键删除"+remarks;
    		}else{
    			result="通过组合条件删除"+remarks+"，支持批量删除";
    		}
    	}else if(menthodName.indexOf("select")>-1){
    		if(menthodName.indexOf("PrimaryKey")>-1){
    			result="通过主键查询"+remarks;
    		}else if(menthodName.indexOf("Blob")>-1){
    			result="通过组合条件查询"+remarks+"，支持分页;返回全部字段";
    		}else{
    			result="通过组合条件查询"+remarks+"，支持分页;不返回大数据字段，如：text类型字段";
    		}
    	}else if(menthodName.indexOf("count")>-1){
    		result="通过组合条件统计"+remarks;
    	}else if(menthodName.indexOf("insert")>-1){
    		result="添加数据到"+remarks;
    	}else if(menthodName.indexOf("update")>-1){
    		if(menthodName.indexOf("PrimaryKey")>-1){
    			result="通过主键更新"+remarks;
    		}else{
    			result="通过组合条件更新"+remarks;
    		}
    		
    	}
    	return result;
    }
    
    public void addGeneralMethodComment(Method method,
            IntrospectedTable introspectedTable) {
        if (suppressAllComments) {
            return;
        }
        
        method.addJavaDocLine("/**"); //$NON-NLS-1$
        method
                .addJavaDocLine(" * "+operMethodComment(method,introspectedTable)+"<br>"); //$NON-NLS-1$
//        method.addJavaDocLine(" * 此方法为自动生成.<br>");
        method.addJavaDocLine(" *");
        method.addJavaDocLine(" * TABLE： "+introspectedTable.getFullyQualifiedTable()+"<br>");
        addJavadocTag(method, false);
        method.addJavaDocLine(" */"); //$NON-NLS-1$
    }

    public void addGetterComment(Method method,
            IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
        if (suppressAllComments) {
            return;
        }

//        StringBuilder sb = new StringBuilder();
//
//        method.addJavaDocLine("/**"); //$NON-NLS-1$
//        method
//                .addJavaDocLine(" * This method was generated by MyBatis Generator."); //$NON-NLS-1$
//
//        sb.append(" * This method returns the value of the database column "); //$NON-NLS-1$
//        sb.append(introspectedTable.getFullyQualifiedTable());
//        sb.append('.');
//        sb.append(introspectedColumn.getActualColumnName());
//        method.addJavaDocLine(sb.toString());
//
//        method.addJavaDocLine(" *"); //$NON-NLS-1$
//
//        sb.setLength(0);
//        sb.append(" * @return the value of "); //$NON-NLS-1$
//        sb.append(introspectedTable.getFullyQualifiedTable());
//        sb.append('.');
//        sb.append(introspectedColumn.getActualColumnName());
//        method.addJavaDocLine(sb.toString());
//
//        addJavadocTag(method, false);
//
//        method.addJavaDocLine(" */"); //$NON-NLS-1$
    	//自定义修改
		if (introspectedColumn.getRemarks() != null && !introspectedColumn.getRemarks().equals("")) {
			method.addJavaDocLine("/**");
			method.addJavaDocLine(" * " + introspectedColumn.getRemarks()+"<br>");
			method.addJavaDocLine(" *");
			method.addJavaDocLine(" * column：" + introspectedTable.getFullyQualifiedTable()+"."+introspectedColumn.getActualColumnName()+"<br>");
			method.addJavaDocLine(" * @return "+introspectedColumn.getActualColumnName());
			method.addJavaDocLine(" */");
		}
    }

    public void addSetterComment(Method method,
            IntrospectedTable introspectedTable,
            IntrospectedColumn introspectedColumn) {
//        if (suppressAllComments) {
//            return;
//        }
//
//        StringBuilder sb = new StringBuilder();
//
//        method.addJavaDocLine("/**"); //$NON-NLS-1$
//        method
//                .addJavaDocLine(" * This method was generated by MyBatis Generator."); //$NON-NLS-1$
//
//        sb.append(" * This method sets the value of the database column "); //$NON-NLS-1$
//        sb.append(introspectedTable.getFullyQualifiedTable());
//        sb.append('.');
//        sb.append(introspectedColumn.getActualColumnName());
//        method.addJavaDocLine(sb.toString());
//
//        method.addJavaDocLine(" *"); //$NON-NLS-1$
//
//        Parameter parm = method.getParameters().get(0);
//        sb.setLength(0);
//        sb.append(" * @param "); //$NON-NLS-1$
//        sb.append(parm.getName());
//        sb.append(" the value for "); //$NON-NLS-1$
//        sb.append(introspectedTable.getFullyQualifiedTable());
//        sb.append('.');
//        sb.append(introspectedColumn.getActualColumnName());
//        method.addJavaDocLine(sb.toString());
//
//        addJavadocTag(method, false);
//
//        method.addJavaDocLine(" */"); //$NON-NLS-1$
		// 自定义修改
		if (introspectedColumn.getRemarks() != null && !introspectedColumn.getRemarks().equals("")) {
			method.addJavaDocLine("/**");
			method.addJavaDocLine(" * " + introspectedColumn.getRemarks()+"<br>");
			method.addJavaDocLine(" *");
			method.addJavaDocLine(" * column："+introspectedTable.getFullyQualifiedTable()+"."+introspectedColumn.getActualColumnName()+"<br>");
			Parameter parm = method.getParameters().get(0);
			StringBuilder sb = new StringBuilder();
			sb.append(" * @param ");
			sb.append(parm.getName());
			method.addJavaDocLine(sb.toString());
			method.addJavaDocLine(" */");
		}
    }

    public void addClassComment(InnerClass innerClass,
            IntrospectedTable introspectedTable, boolean markAsDoNotDelete) {
        if (suppressAllComments) {
            return;
        }

        StringBuilder sb = new StringBuilder();

        innerClass.addJavaDocLine("/**"); //$NON-NLS-1$
        innerClass
                .addJavaDocLine(" * 此类为自动生成."); //$NON-NLS-1$

        sb.append(" * 对应的数据库表为： "); //$NON-NLS-1$
        sb.append(introspectedTable.getFullyQualifiedTable());
        innerClass.addJavaDocLine(sb.toString());

        addJavadocTag(innerClass, markAsDoNotDelete);

        innerClass.addJavaDocLine(" */"); //$NON-NLS-1$
    }
}
